/****************************************************************************
 *
 *   Copyright (c) 2024 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file aux4_control_example.cpp
 *
 * AUX4控制示例模块
 *
 * 这个模块演示了如何在PX4控制算法中使用AUX4数据。
 * AUX4可以用来调整控制参数、触发不同功能等。
 */

#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/module_params.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/px4_work_queue/ScheduledWorkItem.hpp>
#include <uORB/Publication.hpp>
#include <uORB/Subscription.hpp>
#include <uORB/topics/manual_control_setpoint.h>
#include <uORB/topics/vehicle_status.h>
#include <uORB/topics/parameter_update.h>
#include <mathlib/mathlib.h>

using namespace time_literals;

class Aux4ControlExample : public ModuleBase<Aux4ControlExample>, public ModuleParams, public px4::ScheduledWorkItem
{
public:
	Aux4ControlExample();
	~Aux4ControlExample() override;

	/** @see ModuleBase */
	static int task_spawn(int argc, char *argv[]);

	/** @see ModuleBase */
	static int custom_command(int argc, char *argv[]);

	/** @see ModuleBase */
	static int print_usage(const char *reason = nullptr);

	bool init();

	int print_status() override;

private:
	void Run() override;
	void updateParams() override;

		// AUX4数据处理函数
	void processAux4Data(float aux4_value);

	// AUX7数据处理函数
	void processAux7Data(float aux7_value);

	// 根据AUX4值调整控制参数
	void adjustControlGains(float aux4_value);

	// 根据AUX4值触发不同功能
	void triggerFunctions(float aux4_value);

	uORB::Subscription _manual_control_setpoint_sub{ORB_ID(manual_control_setpoint)};
	uORB::Subscription _vehicle_status_sub{ORB_ID(vehicle_status)};
	uORB::Subscription _parameter_update_sub{ORB_ID(parameter_update)};

	// 控制参数
	float _control_gain{1.0f};
	float _last_aux4_value{0.0f};
	bool _aux4_enabled{false};

	// 功能触发状态
	bool _function_a_triggered{false};
	bool _function_b_triggered{false};

	// 参数
	ParamFloat _param_aux4_gain_scale{this, "AUX4_GAIN_SCALE", false, 0.5f};
	ParamFloat _param_aux4_threshold_high{this, "AUX4_THRESH_HIGH", false, 0.8f};
	ParamFloat _param_aux4_threshold_low{this, "AUX4_THRESH_LOW", false, -0.8f};
};

Aux4ControlExample::Aux4ControlExample() :
	ModuleParams(nullptr),
	ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::rate_ctrl)
{
	updateParams();
}

Aux4ControlExample::~Aux4ControlExample()
{
	ScheduleClear();
}

bool Aux4ControlExample::init()
{
	ScheduleOnInterval(50_ms); // 20Hz
	return true;
}

void Aux4ControlExample::Run()
{
	if (should_exit()) {
		ScheduleClear();
		exit_and_cleanup();
		return;
	}

	// 检查参数更新
	if (_parameter_update_sub.updated()) {
		parameter_update_s param_update;
		_parameter_update_sub.copy(&param_update);
		updateParams();
	}

		// 处理手动控制输入
	manual_control_setpoint_s manual_control_setpoint;

	if (_manual_control_setpoint_sub.update(&manual_control_setpoint)) {
		// 检查AUX4数据是否有效
		if (PX4_ISFINITE(manual_control_setpoint.aux4)) {
			float aux4_value = manual_control_setpoint.aux4;

			// 处理AUX4数据
			processAux4Data(aux4_value);

			// 调试输出
			if (fabsf(aux4_value - _last_aux4_value) > 0.01f) {
				PX4_INFO("AUX4 Control: value=%.3f, gain=%.3f", (double)aux4_value, (double)_control_gain);
				_last_aux4_value = aux4_value;
			}
		}

		// 检查AUX7数据是否有效
		if (PX4_ISFINITE(manual_control_setpoint.aux7)) {
			float aux7_value = manual_control_setpoint.aux7;

			// 处理AUX7数据
			processAux7Data(aux7_value);

			// 调试输出
			PX4_INFO("AUX7 Control: value=%.3f", (double)aux7_value);
		}
	}
}

void Aux4ControlExample::processAux4Data(float aux4_value)
{
	// 调整控制增益
	adjustControlGains(aux4_value);

	// 触发功能
	triggerFunctions(aux4_value);
}

void Aux4ControlExample::processAux7Data(float aux7_value)
{
	// AUX7数据处理逻辑
	// 例如：控制云台、触发特殊功能等

	if (aux7_value > 0.8f) {
		PX4_INFO("AUX7: 触发特殊功能A (aux7=%.3f)", (double)aux7_value);
		// 在这里添加特殊功能A的实现

	} else if (aux7_value < -0.8f) {
		PX4_INFO("AUX7: 触发特殊功能B (aux7=%.3f)", (double)aux7_value);
		// 在这里添加特殊功能B的实现

	} else if (fabsf(aux7_value) > 0.1f) {
		// 连续控制模式
		PX4_INFO("AUX7: 连续控制模式 (aux7=%.3f)", (double)aux7_value);
		// 在这里添加连续控制逻辑
	}
}

void Aux4ControlExample::adjustControlGains(float aux4_value)
{
	// 根据AUX4值调整控制增益
	// aux4_value范围: [-1, 1]
	// 当aux4 > 0.5时增加增益，当aux4 < -0.5时减少增益

	if (aux4_value > 0.5f) {
		// aux4 > 0.5时的控制逻辑 - 增加增益
		_control_gain = 1.0f + (aux4_value - 0.5f) * _param_aux4_gain_scale.get() * 2.0f;
		_aux4_enabled = true;

	} else if (aux4_value < -0.5f) {
		// aux4 < -0.5时的控制逻辑 - 减少增益
		_control_gain = 1.0f - fabsf(aux4_value + 0.5f) * _param_aux4_gain_scale.get() * 2.0f;
		_control_gain = math::max(_control_gain, 0.1f); // 最小增益限制
		_aux4_enabled = true;

	} else {
		// 中间区域 - 正常增益
		_control_gain = 1.0f;
		_aux4_enabled = false;
	}
}

void Aux4ControlExample::triggerFunctions(float aux4_value)
{
	// 根据AUX4值触发不同功能

	// 功能A: aux4 > 0.8时触发
	if (aux4_value > _param_aux4_threshold_high.get()) {
		if (!_function_a_triggered) {
			PX4_INFO("AUX4: 触发功能A (aux4=%.3f)", (double)aux4_value);
			_function_a_triggered = true;
			// 在这里添加功能A的具体实现
		}
	} else {
		_function_a_triggered = false;
	}

	// 功能B: aux4 < -0.8时触发
	if (aux4_value < _param_aux4_threshold_low.get()) {
		if (!_function_b_triggered) {
			PX4_INFO("AUX4: 触发功能B (aux4=%.3f)", (double)aux4_value);
			_function_b_triggered = true;
			// 在这里添加功能B的具体实现
		}
	} else {
		_function_b_triggered = false;
	}
}

void Aux4ControlExample::updateParams()
{
	ModuleParams::updateParams();
}

int Aux4ControlExample::task_spawn(int argc, char *argv[])
{
	Aux4ControlExample *instance = new Aux4ControlExample();

	if (instance) {
		_object.store(instance);
		_task_id = task_id_is_work_queue;

		if (instance->init()) {
			return PX4_OK;
		}

	} else {
		PX4_ERR("alloc failed");
	}

	delete instance;
	_object.store(nullptr);
	_task_id = -1;

	return PX4_ERROR;
}

int Aux4ControlExample::custom_command(int argc, char *argv[])
{
	return print_usage("unknown command");
}

int Aux4ControlExample::print_usage(const char *reason)
{
	if (reason) {
		PX4_WARN("%s\n", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
### 描述
AUX4控制示例模块

这个模块演示了如何在PX4控制算法中使用AUX4数据。
AUX4可以用来调整控制参数、触发不同功能等。

### 用法
$ aux4_control_example start
$ aux4_control_example stop
$ aux4_control_example status
)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("aux4_control_example", "system");
	PRINT_MODULE_USAGE_COMMAND("start");
	PRINT_MODULE_USAGE_COMMAND("stop");
	PRINT_MODULE_USAGE_COMMAND("status");

	return 0;
}

int Aux4ControlExample::print_status()
{
	PX4_INFO("AUX4 Control Example Status:");
	PX4_INFO("  Control Gain: %.3f", (double)_control_gain);
	PX4_INFO("  AUX4 Enabled: %s", _aux4_enabled ? "Yes" : "No");
	PX4_INFO("  Function A: %s", _function_a_triggered ? "Active" : "Inactive");
	PX4_INFO("  Function B: %s", _function_b_triggered ? "Active" : "Inactive");

	return 0;
}

extern "C" __EXPORT int aux4_control_example_main(int argc, char *argv[])
{
	return Aux4ControlExample::main(argc, argv);
}
